const numberHandle = (e: any) => {
  const value = e.target.value
  const matchs = value.match(/[^0-9]+/g)
  if (matchs) {
    let newVal = value.replace(/[^0-9]+/g, '')
    if (newVal) {
      newVal = parseInt(newVal, 10)
    }
    e.target.value = newVal
    e.target.dispatchEvent(new Event('input'))
  } else {
    if (value.length > 1 && /^0/g.test(value)) {
      e.target.value = parseInt(value, 10)
      e.target.dispatchEvent(new Event('input'))
    }
  }
}

const isInput = (el: HTMLElement) => {
  const tagName: string = el.tagName
  if (['input', 'textarea'].includes(tagName.toLocaleLowerCase())) {
    return true
  } else {
    return false
  }
}

export default {
  install(Vue: any) {
    Vue.mixin({
      directives: {
        loadmore: {
          bind(el: HTMLElement) {
            if (!isInput(el)) {
              console.warn('directive[number] is must used on input or textarea element')
              return
            }
            el.addEventListener('input', numberHandle)
          },
          unbind(el: HTMLElement) {
            if (!isInput(el)) {
              return
            }
            el.removeEventListener('input', numberHandle)
          }
        }
      }
    })
  }
}
